<script setup lang="ts">
import { ref, reactive, Ref, computed } from "vue";
let num: Ref<number> = ref(0)
let num1: number = 2
let twoCount = computed<number>(() => {
  return num.value + num1
})
let threeCount = computed({
  get: () => {
    return num.value + num1
  },
  set: (value) => {

  }
})

interface commodity {
  id: number
  name: string
  num: number
  price: number
}

let commoditys = reactive<commodity[]>([])
commoditys.push({
  id: 1,
  name: "裤子",
  num: 1,
  price: 100
})
commoditys.push({
  id: 2,
  name: "帽子",
  num: 1,
  price: 10
})
commoditys.push({
  id: 3,
  name: "上衣",
  num: 1,
  price: 200
})

const addAndSub = (item: commodity, addBoo: boolean): void => {
  if (addBoo) {
    if (item.num < 99) {
      item.num++
    }
  } else {
    if (item.num > 1) {
      item.num--
    }
  }
}

const del = (index: number) => {
  console.log("删除", index)
  commoditys.splice(index, 1)
}

let countPrice = computed(() => {
  return commoditys.reduce((prev, next) => {
    return prev + (next.num * next.price)
  }, 0)
})

</script>

<template>

  <h1>computed 计算属性</h1>
  计算属性就是当依赖的属性的值发生变化的时候，才会触发他的更改，如果依赖的值，不发生变化的时候，使用的是缓存中的属性值。

  <H2>基础练习</H2>
  <input type="text" v-model="num">
  <br>
  {{ num }}+{{ num1 }}={{ twoCount }}
  <br>
  {{ num }}+{{ num1 }}={{ threeCount }}
  <br>

  <h2>购物车练习</h2>
  <table style="width: 800px;" border>
    <thead>
      <tr>
        <th align="center">商品名称</th>
        <th align="center">购物数量</th>
        <th align="center">单价</th>
        <th align="center">总价</th>
        <th align="center">操作</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(itme, index) in commoditys" :key="index">
        <td>{{ itme.name }}</td>
        <td align="right">
          <input type="button" value="-" @click="addAndSub(itme, false)">
          {{ itme.num }}
          <input type="button" value="+" @click="addAndSub(itme, true)">
        </td>
        <td align="right">{{ itme.price }}</td>
        <td align="right">{{ itme.num * itme.price }}</td>
        <td align="center">
          <input type="button" value="删除" @click="del(index)">
        </td>
      </tr>
    </tbody>
    <tfoot>
      <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td>总计：{{countPrice}}（元）</td>
      </tr>
    </tfoot>
  </table>

</template>

<style>
</style>
